<?php

/**
* @desc Manager with filter list.
* 
*/
class Kernel_Manager_FilteredList extends Kernel_Manager_List 
{
    
    /**
    * @desc Filter name.
    * 
    */
    const FILTER_NAME = 'list';
    
    /**
    * @desc Filters list.
    * 
    * @param array
    */
    public $filters = array(); 
    
    /**
    * @desc Active filter.
    * 
    * @param string
    */
    protected $_filter; 
    
    
    public function __construct($params = array()) 
    {
        parent::__construct($params);
        
        // set filter list
        $this->_filter = $this->_getActiveFilter();
        
        // set through default
        Backend_Filter_Structure::set(self::FILTER_NAME, $this->_filter);
    }
    
    public function process() 
    {
        parent::process();
        
        $filters = array();
        foreach ($this->_getFilters() as $url => $name) {
            $filters[] = array (
                  'name' => $name,
                'active' => $url == $this->_filter,
                   'url' => array(self::FILTER_NAME => $url),
            );
        }
        
        Application::getResponse()->assign('filter_' . self::FILTER_NAME, $filters);
    }
    
    /**
     * @desc Return manager components package.
     *
     * @return  string
     */
    protected function _package() 
    {
        return parent::_package() . '_' . str_camelize($this->_filter);
    }
    
    /**
    * @desc Convert filters list as uri => name. Return filters. 
    * 
    * @return array
    */
    private function _getFilters() 
    {
        static $cach = array();
        
        if (empty($cach)) {
            if (empty($this->filters)) {
                trigger_error('Filters must be specified in class definition');
            }
            if (is_numeric_array($this->filters)) {
                $manager = Backend_Filter_Structure::get('manager');
                
                foreach ($this->filters as $filter) {
                    $cach[$filter] = $manager . '_' . $filter;
                }
            } else {
                $cach = $this->filters;
            }
        }
        
        return $cach;
    }
    
    /**
    * @desc Get active filter.
    * 
    * @return string
    */
    private function _getActiveFilter() 
    {
        $filter = Application::getRequest()->get(self::FILTER_NAME);
        $filters = array_keys($this->_getFilters());
        if (!in_array($filter, $filters)) {
            // reload with correct filter
            $this->_location(array(self::FILTER_NAME => current($filters)));
        }
        
        return $filter;
    }
    
}